<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>dig</title>
</head>

<body>
    <div>打开浏览器控制台查看结果</div>
    <script>
        const dig = (obj, target) =>
            target in obj
                ? obj[target]
                : Object.values(obj).reduce((acc, val) => {
                    if (acc !== undefined) {
                        return acc;
                    }
                    if (typeof val === 'object') {
                        return dig(val, target);
                    }
                }, undefined);
        const data = {
            level1: {
                level2: {
                    level3: 'some data'
                }
            }
        };
        console.log(dig(data, 'level3')); // 'some data'
        console.log(dig(data, 'level4')); // undefined
    </script>
</body>

</html>